<script setup>
import { User, Lock, Picture, Message } from "@element-plus/icons-vue";
import ResetPassword from "../../components/ResetPassword/index.vue";
import { ref, watch, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/index";
import { ElMessage } from "element-plus";
import {
  setUsername,
  setPassword,
  setRememberMe,
  removeUsername,
  removePassword,
  removeRememberMe,
  getUsername,
  getPassword,
  getRememberMe,
} from "@/utils/token";
import {
  userRegisterService,
  userLoginService,
  getCaptcha,
  sendEmailCode,
} from "@/api/user";
const isRegister = ref(false);
const form = ref(); //注册 和 登陆 同时使用同一个 「v-if 所以不会出错」
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const visable = ref(false);
const redirect = ref(undefined);

//  验证码
let captchaKey = ref("");
const captchaImg = ref("");
// 添加定时器相关逻辑
const timer = ref(null);
const countdown = ref(0);
const sendCodeText = ref("发送验证码");

// 提交的form对象
const formModel = ref({
  user_name: "",
  password: "",
  repassword: "",
  captcha: "",
  email: "",
  code: "",
  rememberMe: false,
});

const rules = {
  user_name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  repassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  code: [
    { required: true, message: "请输入邮箱验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码长度应为6位", trigger: "blur" },
  ],
};
// 切换时清空表单数据
watch(isRegister, () => {
  formModel.value = {
    user_name: "",
    password: "",
    repassword: "",
    captcha: "",
    email: "",
    code: "",
  };
});
const getCookie = () => {
  const username = getUsername();
  const password = getPassword();
  const rememberMe = getRememberMe();
  formModel.value = {
    ...formModel.value,
    user_name: username ? username : formModel.value.user_name,
    password: password ? password : formModel.value.password,
    rememberMe: rememberMe ? rememberMe : false,
  };
};
// 注册
const register = async () => {
  try {
    let email = formModel.value.email;
    const fullEmail = email.includes("@") ? email : email + "@qq.com";
    await form.value.validate();
    console.log("开始注册请求");
    await userRegisterService({
      ...formModel.value,
      captchaKey: captchaKey.value,
      email: fullEmail,
    });
    ElMessage.success("注册成功");
    refreshCaptcha();
    isRegister.value = false;
  } catch (error) {
    console.log(error);
    // 10110 验证码过期
    if (error.code == "10110") {
      refreshCaptcha();
    }
  }
};
// 登陆
const login = async () => {
  try {
    await form.value.validate();
    console.log("开始登录");
    await form.value.validate();
    // 设置 Cookie
    // 记住密码
    if (formModel.value.rememberMe) {
      setUsername(formModel.value.user_name);
      setPassword(formModel.value.password);
      setRememberMe(formModel.value.rememberMe);
    } else {
      removeUsername();
      removePassword();
      removeRememberMe();
    }

    // 验证
    await userStore.userLogin({
      ...formModel.value,
      captchaKey: captchaKey.value,
    });

    ElMessage.success("登录成功");
    router.push(redirect.value || "/");
  } catch (error) {
    console.log(error);
    // 10110 验证码过期
    if (error.code == "10110") {
      refreshCaptcha();
    }
  }
};

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const { result } = await getCaptcha();
    captchaImg.value = result.captcha;
    captchaKey.value = result.captchaKey;
  } catch (error) {
    console.error("获取验证码失败:", error);
  }
};
// 添加发送验证码的方法
const sendCode = async () => {
  if (countdown.value > 0) return;
  let email = formModel.value.email;
  if (!email) {
    ElMessage.error("请输入邮箱");
    return;
  }
  const fullEmail = email.includes("@") ? email : email + "@qq.com";

  // 立即开始倒计时
  countdown.value = 60;
  timer.value = setInterval(() => {
    countdown.value--;
    sendCodeText.value = `${countdown.value}秒后重试`;
    if (countdown.value <= 0) {
      clearInterval(timer.value);
      sendCodeText.value = "发送验证码";
    }
  }, 1000);

  try {
    await sendEmailCode({ email: fullEmail });
    ElMessage.success("验证码发送成功");
  } catch (error) {
    // 如果发送失败，立即重置倒计时
    clearInterval(timer.value);
    countdown.value = 0;
    sendCodeText.value = "发送验证码";
    console.error("发送验证码失败:", error);
  }
};

// 页面加载时获取验证码
onMounted(() => {
  redirect.value = route.query.redirect
    ? decodeURIComponent(route.query.redirect)
    : undefined;
  refreshCaptcha();
  getCookie();
});
// 页面卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg">电商后台管理系统</el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        :model="formModel"
        v-if="isRegister"
        :rules="rules"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="user_name">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.user_name"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
            v-model="formModel.repassword"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <div class="email-input-container">
            <el-input
              v-model="formModel.email"
              placeholder="请输入邮箱"
              class="email-prefix"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
              <template #suffix>
                <span class="email-suffix">@qq.com</span>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="code">
          <div class="code-container">
            <el-input
              v-model="formModel.code"
              placeholder="请输入邮箱验证码"
              class="code-input"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
            <el-button
              :disabled="countdown > 0"
              @click="sendCode"
              class="send-code-btn"
            >
              {{ sendCodeText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="formModel.captcha"
              :prefix-icon="Picture"
              placeholder="请输入验证码"
              class="captcha-input"
            >
            </el-input>
            <div
              class="captcha-img"
              v-html="captchaImg"
              @click="refreshCaptcha"
            ></div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="register"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        :model="formModel"
        :rules="rules"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="user_name">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.user_name"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="formModel.captcha"
              placeholder="请输入验证码"
              class="captcha-input"
            >
              <template #prefix>
                <el-icon><Picture /></el-icon>
              </template>
            </el-input>
            <div
              class="captcha-img"
              v-html="captchaImg"
              @click="refreshCaptcha"
            ></div>
          </div>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="formModel.rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false" @click="visable = true"
              >忘记密码？</el-link
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <reset-password v-model:dialogFormVisible="visable"></reset-password>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 700;
    font-size: 24px;
    color: #fff;
    background: url("@/assets/login_bg.jpg") no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .captcha-input {
    flex: 1;
    :deep(.el-input__wrapper) {
      height: 40px;
      line-height: 40px;
    }
  }
}

.captcha-img {
  width: 120px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;

  svg {
    width: 100%;
    height: 100%;
    vertical-align: middle;
  }
}

.code-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .code-input {
    flex: 1;
    :deep(.el-input__wrapper) {
      height: 40px;
      line-height: 40px;
    }
  }

  .send-code-btn {
    width: 120px;
    height: 40px;
    white-space: nowrap;
  }
}

.email-input-container {
  position: relative;
  width: 100%;
  .email-suffix {
    color: #999;
    font-size: 14px;
  }
  :deep(.el-input__wrapper) {
    height: 40px;
    line-height: 40px;
  }
}

:deep(.el-input__wrapper) {
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
}
</style>
